﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Infrastructure;
using NLog;
using ServiceStack;
using WsdShop.IService;
using WsdShop.Model;
using WsdShop.Model.SearchModels;
using WsdShop.Model.ViewModels;

namespace WsdShop.Service
{
    public class UserGroupService : IUserGroupService
    {
        protected IUserInfoService userService;
        protected IUserGroupRoleService grouproleService;
        private static Logger NLog = LogManager.GetLogger("Request");

        public UserGroupService(IUserInfoService _userService, IUserGroupRoleService _grouproleservice)
        {
            this.userService = _userService;
            this.grouproleService = _grouproleservice;
        }

        public List<UserGroupViewModel> UserGroupManage(UserGroupSearchModel search, out int total)
        {
            List<UserGroupViewModel> list = new List<UserGroupViewModel>();
            StringBuilder wherestr = new StringBuilder();
            wherestr.Append(" 1=1 ");
            if (!string.IsNullOrWhiteSpace(search.Keywords))
            {
                wherestr.AppendFormat(" and GroupName like '%{0}%'  ", search.Keywords);
            }
            //int totalcount = 0;
            var grouplist = BaseService.LoadPageEntities<UserGroup>(search.Skip, search.Take, out total, wherestr.ToString(), search.OrderByFields);
            if (grouplist != null && grouplist.Count > 0)
            {
                foreach (var item in grouplist)
                {
                    var listitem = item.ConvertTo<UserGroupViewModel>();
                    var userlist = userService.GetUserList(string.Format(" GroupId={0} ", item.Id));
                    if (userlist != null && userlist.Count > 0)
                    {
                        var usernamelist = new List<string>();
                        userlist.ForEach(m => usernamelist.Add(m.UserName));
                        listitem.UserNameList = usernamelist;
                    }
                    list.Add(listitem);
                }
            }
            return list;
        }


        public Result UserGroupEdit(UserGroup userGroup, int cacheUserId)
        {
            if (userGroup == null)
            {
                return Result.Failure("传入参数有误");
            }

            if (userGroup.Id == 0)
            {
                userGroup.AddUserId = cacheUserId;
                BaseService.AddEntity(userGroup);
            }
            else
            {
                userGroup.EditUserId = cacheUserId;
                userGroup.EditTime = DateTime.Now;
                BaseService.UpdateEntity(userGroup);
            }
            return Result.Success();
        }


        public List<SystemMenuModel> GetMenuList(int groupId)
        {
            var allMenu = GetMenuFromJson();
            if (allMenu == null || allMenu.Count == 0)
            {
                return new List<SystemMenuModel>();
            }
            var result = allMenu.OrderBy(m => m.Sort).ToList();
            var currentAuth = grouproleService.GetByGroupId(groupId);
            if (currentAuth != null && currentAuth.Count > 0)
            {
                currentAuth.ForEach(
               m =>
                   (result.FirstOrDefault(n => n.Id == m.MenuId) ?? new SystemMenuModel()).state = new { selected = true });
            }
            var parentMenuList = new List<SystemMenuModel>();
            foreach (var item in result)
            {
                if (item.ParentId != 0 && result.All(m => m.Id != item.ParentId) && parentMenuList.All(m => m.Id != item.ParentId))
                {
                    parentMenuList.Add(allMenu.FirstOrDefault(m => m.Id == item.ParentId));
                }
            }
            return result.Concat(parentMenuList).OrderBy(m => m.Sort).ToList();
        }


        public Result UpdateGroupRole(List<string> AuthList, int GroupId, int cacheUserId)
        {
            AuthList = AuthList ?? new List<string>();
            //获取所有菜单
            var allMenu = GetMenuFromJson();
            if (allMenu == null || allMenu.Count == 0)
            {
                return Result.Failure("获取菜单权限失败");
            }

            var parentMenuList = new List<SystemMenuModel>();
            foreach (var item in allMenu)
            {
                if (item.ParentId != 0 && allMenu.All(m => m.Id != item.ParentId) && parentMenuList.All(m => m.Id != item.ParentId))
                {
                    parentMenuList.Add(allMenu.FirstOrDefault(m => m.Id == item.ParentId));
                }
            }
            allMenu.AddRange(parentMenuList);

            var updateAuthList =
                allMenu.Where(m => AuthList.Contains(m.Id.ToString()) && m.sref != "#")
                    .Select(m => m.Id.ToString()).ToList() ?? new List<string>();

            //获取现有权限
            var currentAuth = grouproleService.GetByGroupId(GroupId);
            if (currentAuth != null && currentAuth.Count > 0)
            {
                foreach (var item in currentAuth)
                {
                    if (updateAuthList.Contains(item.MenuId.ToString()))
                    {
                        updateAuthList.Remove(item.MenuId.ToString());
                    }
                    else
                    {
                        item.IsDeleted = true;
                        item.EditTime = DateTime.Now;
                        item.EditUserId = cacheUserId;
                        BaseService.UpdateEntity(item);
                    }
                }
            }

            if (updateAuthList != null && updateAuthList.Count > 0)
            {
                updateAuthList.ForEach(m => BaseService.AddEntity(new UserGroupRole { AddUserId = cacheUserId, MenuId = m.ToInt(), UserGroupId = GroupId }));
            }
            return Result.Success();
        }

        public Result DelGroupRole(int Id, int cacheUserId)
        {
            if (Id == 0)
            {
                return Result.Failure("传入Id不能为0");
            }

            var group = BaseService.LoadEntity<UserGroup>(m => m.Id == Id);
            group.IsDeleted = true;
            group.EditTime = DateTime.Now;
            group.EditUserId = cacheUserId;
            BaseService.UpdateEntity(group);

            var grouproles = BaseService.LoadEntities<UserGroupRole>(m => m.UserGroupId == Id);
            if (grouproles != null && grouproles.Count > 0)
            {
                foreach (var item in grouproles)
                {
                    item.IsDeleted = true;
                    item.EditTime = DateTime.Now;
                    item.EditUserId = cacheUserId;
                    BaseService.UpdateEntity(item);
                }
            }
            return Result.Success();
        }

        private List<SystemMenuModel> GetMenuFromJson()
        {
            try
            {
                var model = File.ReadAllText("~/app/js/sidebar-menu-admin.json".MapHostAbsolutePath()).FromJson<List<SystemMenuModel>>();
                return model;
            }
            catch (Exception ex)
            {
                NLog.Debug("获取菜单信息异常：" + ex.Message + "，" + ex.StackTrace);
                return null;
            }

        }

        public List<SystemMenuModel> GetUserMenu(int currentUserGroupId, bool isadmin)
        {
            var menuList = new List<SystemMenuModel>();
            if (currentUserGroupId == 0)
            {
                return menuList;
            }
            var allMenuList = GetMenuFromJson();
            if (isadmin)
            {
                allMenuList.ForEach(m =>
                {
                    if (m.ParentId != 0)
                    {
                        var parentMenu = allMenuList.FirstOrDefault(n => n.Id == m.ParentId) ??
                                         new SystemMenuModel();
                        if (parentMenu.submenu == null)
                        {
                            parentMenu.submenu = new List<SystemMenuModel>();
                        }
                        parentMenu.submenu.Add(m);
                        if (menuList.All(n => n.Id != m.ParentId))
                        {
                            menuList.Add(parentMenu);
                        }

                    }
                    else
                    {
                        if (!menuList.Any(a => a.Id == m.Id))
                        {
                            menuList.Add(m);
                        }
                    }
                });
            }
            else
            {
                var userauth = grouproleService.GetByGroupId(currentUserGroupId);
                if (userauth != null && userauth.Count > 0)
                {
                    foreach (var item in userauth)
                    {
                        var currentMenu = allMenuList.FirstOrDefault(m => m.Id == item.MenuId);
                        if (currentMenu == null)
                        {
                            continue;
                        }
                        if (currentMenu.ParentId != 0)
                        {
                            var parentMenu = allMenuList.FirstOrDefault(m => m.Id == currentMenu.ParentId) ??
                                             new SystemMenuModel();
                            if (parentMenu.submenu == null)
                            {
                                parentMenu.submenu = new List<SystemMenuModel>();
                            }
                            parentMenu.submenu.Add(currentMenu);
                            if (menuList.All(m => m.Id != currentMenu.ParentId))
                            {
                                menuList.Add(parentMenu);
                            }

                        }
                        else
                        {
                            menuList.Add(currentMenu);
                        }
                    }
                    menuList.OrderBy(m => m.Sort).ToList();
                }
            }
            return menuList;
        }


        public List<UserGroup> GetUserGroupList()
        {
            return BaseService.LoadEntities<UserGroup>(m => m.Id > 0);
        }

    }
}
